package com.bobo.netty.server.telnet;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyTelnetServer {
    private static final Integer PORT = 8080;
    private ServerBootstrap serverBootstrap;
    private EventLoopGroup boss ;
    private EventLoopGroup worker ;
    private static final StringDecoder DECODER = new StringDecoder();
    private static final StringEncoder ENCODER = new StringEncoder();

    public void open () throws InterruptedException {
        serverBootstrap = new ServerBootstrap();
        boss = new NioEventLoopGroup(1);
        worker = new NioEventLoopGroup();
        serverBootstrap.option(ChannelOption.SO_BACKLOG,2000);
        serverBootstrap.group(boss,worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                        pipeline.addLast(DECODER);
                        pipeline.addLast(ENCODER);
                        pipeline.addLast(new NettyTelnetHandler());
                    }
                });
        ChannelFuture sync = serverBootstrap.bind(PORT).sync();
        sync.channel().closeFuture().sync();
    }
    public void close(){
        boss.shutdownGracefully();
        worker.shutdownGracefully();
    }

//    public static void main(String[] args) throws InterruptedException {
//        NettyTelnetServer nettyTelnetServer = new NettyTelnetServer();
//        nettyTelnetServer.open();
//    }
}
